import datetime
import uuid


from fastapi import APIRouter, HTTPException

from config.common_config import DATABASE_CONFIG
from models.request_models import SearchRequest, SearchResponse, SaveMemoryRequest, SaveMemoryResponse
from models.memory_record import MemoryRecord, ContentType, Role
from database.milvus_client import MilvusClient
from database.embedding_model import EmbeddingModel
from models.workflow.inputModel import InputModel
from server.memory_record_server import MemoryRecordServer
# from workflows.memoryFlow import MemoryFlow
from collections import defaultdict

router = APIRouter(prefix="/mem/api/v1", tags=["chat"])

# 初始化组件
memory_record_server = MemoryRecordServer(
    host=DATABASE_CONFIG["HOST"],
    port=DATABASE_CONFIG["PORT"],
    user=DATABASE_CONFIG["USER"],
    pwd=DATABASE_CONFIG["PASSWORD"]
)
embedding_model = EmbeddingModel()
import logging

# chatFlow = MemoryFlow()


logger = logging.getLogger(__name__)

@router.post("/search_memory_history", response_model=SearchResponse)
async def search_memory_history(request: SearchRequest):
    try:
        rId = str(uuid.uuid4())
        print("查询记忆开始" + rId+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        query_embedding = embedding_model.get_embedding(request.keyWord)
        records = memory_record_server.search_records(
            saas_id=request.saasId,
            user_id=request.userId,
            query_embedding=query_embedding,
            #content_type=request.contentType,
            #role=request.role,
            top_k=request.topk,
            min_score=request.min_score,
            date=request.date

        )



        if not records:
            print("查询记忆结束" + rId + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            return SearchResponse(chatHistory="没有找到相关记录")

        content_by_type = defaultdict(list)
        for record in records:
            #record_type = record.get("type", "未分类")
            record_type=request.date
            content_by_type[record_type].append(record["content"])

        chat_history = []
        for type_key, contents in content_by_type.items():
            section = f"【{type_key}】\n" + "\n".join(contents)
            chat_history.append(section)
        # chat_history = "\n\n".join(chat_history)


        # chat_history = []
        # for r in records:
        #     content= f"{r['content']}"
        #     # content = f"{r['role']}: {r['content']}"
        #     if r['optimized_content']:
        #         content += f" (总结: {r['optimized_content']})"
        #     chat_history.append(content)
        #     if r['relation']:
        #         content += f" (关系: {r['relation']})"
        #     chat_history.append(content)
        #     if r['title']:
        #         content += f" (title: {r['title']})"
        #     chat_history.append(content)
        #     if r['type']:
        #         content += f" (type: {r['type']})"
        #     chat_history.append(content)
        res= SearchResponse(chatHistory="\n\n".join(chat_history))

        logger.info(res)
        print("查询记忆结束" + rId+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        return res

    except Exception as e:
        print("查询记忆失败结束" + rId + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/save_memory_record", response_model=SaveMemoryResponse)
async def save_chat_record(request: SaveMemoryRequest):
    try:
        rId = str(uuid.uuid4())
        print("保存记忆开始" + rId+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        record = MemoryRecord(
            saas_id=request.saasId,
            user_id=request.userId,
            content=request.content,
            optimized_content=request.optimizedContent,
            happen_time=request.happenTime,
            title=request.title,
            relation=request.relation,
            type=request.type,
            sec_type=request.sec_type,
            detail=request.detail
        )

        embedding = embedding_model.get_embedding(record.content)
        record_id = memory_record_server.insert_record(record, embedding)
        rId = str(uuid.uuid4())
        print("保存记忆结束" + rId+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        if request.sec_type==None:
            request.sec_type="1"
        return SaveMemoryResponse(
            optimizedContent=request.optimizedContent,
            type=request.type,
            sec_type=request.sec_type,
            recordId=record_id
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))






